<template>
  <!-- 头像组件，点击头像打开抽屉 -->
  <el-avatar :size="60" :src="modelValue" @click="drawer=true">
    <img src="/2.png" />
  </el-avatar>

  <!-- 抽屉组件，显示图库 -->
  <el-drawer v-model="drawer" title="图库" size="50%">
    <!-- 文件上传组件，用于选择图片 -->
    <el-upload
      class="avatar-uploader"
      :show-file-list="false" 
      :auto-upload="false" 
      :on-change="change">
      <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <!-- 图库展示区域 -->
    <div class="tuku">
      <div v-for="item in tukuDate" :key="item" class="img">
        <!-- 图片项，点击后更新头像并关闭抽屉 -->
        <el-image style="width: 100px; height: 100px" :src="item.url" fit="cover" @click="modelValue=item.url;drawer=false"/>
      </div>
    </div>
  </el-drawer> 
</template>

<script setup lang="ts">
// 导入 API 和 Vue 钩子
import { uploadApi } from "@/api";
import { ref, onMounted, defineModel } from "vue";

// 定义双向绑定的 modelValue
const modelValue = defineModel()

// 存储图库数据的响应式变量
const tukuDate = ref<any>([])

// 控制抽屉显示状态的响应式变量
const drawer = ref(false)

// 组件挂载时调用，初始化图库数据
onMounted(() => {
  callUploadSelectApi()
})

// 调用 API 获取图库数据
const callUploadSelectApi = () => {
  uploadApi.select.call().then(res => {
    tukuDate.value = res
  })
}

// 处理文件选择事件
const change = (uploadFile: any, uploadFiles: any) => {
  let name = uploadFile.name
  let jsfile = uploadFile.raw
  let reader = new FileReader()
  reader.readAsDataURL(jsfile)
  reader.onload = (file) => {
    calluploadApi(name, file.target?.result)
  }
}

// 调用 API 上传图片后再次调查询图库数据
const calluploadApi = (name: string, base64: any) => {
  uploadApi.upload.call({ name, base64 }).then(res => {
    callUploadSelectApi()
  })
}
</script>

<style scoped>
/* 头像上传器样式 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 图库容器样式 */
.tuku {
  display: flex;
  flex-direction: row;
  justify-content: start;
  flex-wrap: wrap;
}

/* 单个图片项样式 */
.img {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 5px;
  padding-bottom: 0px;
  margin: 5px;
}
</style>

<style>
/* 文件上传组件样式 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

/* 文件上传组件悬停样式 */
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

/* 上传图标样式 */
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>